package db;

import bean.Article;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class ArticleDao {

    private QueryRunner runner;

    private static final String INSERTARTICLE = "insert into article(content,publish,owner) values(?,?,?)";

    private static final String FINDBYUSERSQL = "select id,content,publish,owner from article where owner = ?" +
            " order by publish desc";

    public ArticleDao(QueryRunner runner) {
        this.runner = runner;
    }

    public void create(Article article) throws IOException {
        try {
            runner.execute(INSERTARTICLE, article.getContent(), article.getPublish(), article.getOwner());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new IOException(e);
        }
    }

    public List<Article> findByID(int owern) throws IOException {
        List<Article> list = null;
        try {
            list = runner.query(FINDBYUSERSQL, new BeanListHandler<>(Article.class), owern);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new IOException(e);
        }
        return list;
    }
}
